/* eslint-disable no-unused-vars */
import React, { Component } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import MediumProfileBar from 'component/ProfileBars/MediumProfileBar';
import RichTextEditor from 'component/RichTexts/RichTextEditor';
import AnswerService from 'service/RequestServices/AnswerService';
import MeService from 'service/MeService';
import { URL } from 'service/URLService';
import { GrayLight1 } from 'style/Color';
import LoadingPage from 'widget/LoadingPage';
import Button from 'widget/Button';
import Card from 'widget/Card';

const AnswerQuestionCardRoot = styled(Card)`
  min-height: 420px;
  position: relative;
  padding: 16px 20px;
  box-sizing: border-box;
`;

const Container = styled.div`
  margin-top: 8px;
`;

const Badge = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
`;

const FooterBadge = styled(Badge)`
  height: 56px;
  padding: 10px 0;
`;

const Privacy = styled.div`
  display: inline-flex;
  align-items: center;
  color: ${GrayLight1};
  font-size: 15px;
  cursor: pointer;
`;

const CheckBox = styled.input`
  margin-right: 8px;
`;

class AnswerQuestionCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      privacy: false
    };
    this.editorRef = React.createRef();

    this.setPrivacy = () => {
      this.setState({ privacy: true });
    };

    this.submit = this.submit.bind(this);
  }

  componentDidMount() {
    this.editorRef.current.focus();
  }

  submit() {
    let { loading } = this.state;
    const { questionID } = this.props;
    const { privacy } = this.state;
    const content = JSON.stringify(this.editorRef.current.getRaw());
    const type = privacy ? 1 : 0;
    loading = true;
    this.setState({ loading }, () => {
      AnswerService.postAnswer({ questionID, content, type }).then(({ record, ra }) => {
        if (ra === 1) {
          URL.go(URL.answer(record.id));
        }
      });
    });
  }

  render() {
    const { loading } = this.state;
    if (loading) {
      return (
        <AnswerQuestionCardRoot>
          <LoadingPage />
        </AnswerQuestionCardRoot>
      );
    }
    return (
      <AnswerQuestionCardRoot>
        <MediumProfileBar data={MeService.GetMe()} />
        <Container>
          <RichTextEditor ref={this.editorRef} type="answer" />
        </Container>
        <FooterBadge>
          <Button theme="primary" bold onClick={this.submit}>
            <FormattedMessage id="post.answer" />
          </Button>
        </FooterBadge>
      </AnswerQuestionCardRoot>
    );
  }
}

AnswerQuestionCard.propTypes = {
  questionID: PropTypes.number.isRequired
};

export default AnswerQuestionCard;
